package com.equdao.car_violation_inquiry.service.impl;

import com.alibaba.fastjson.JSON;
import com.equdao.car_violation_inquiry.dao.ChannelManageMapper;
import com.equdao.car_violation_inquiry.dao.ClientDaoMapper;
import com.equdao.car_violation_inquiry.dao.ViolationInfoDaoMapper;
import com.equdao.car_violation_inquiry.enums.ResultEnum;
import com.equdao.car_violation_inquiry.pojo.*;

import com.equdao.car_violation_inquiry.properties.HengDaProperties;
import com.equdao.car_violation_inquiry.service.ClientService;
import com.equdao.car_violation_inquiry.utils.CityCodeUtils;
import com.equdao.car_violation_inquiry.utils.HttpAPIService;
import com.equdao.car_violation_inquiry.utils.HttpResult;
import com.equdao.car_violation_inquiry.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: 杨忠强
 * @Date: 2018/5/28 16:15
 * @Description:
 */
@Service
public class ClientServiceImpl implements ClientService {

    @Resource
    private ClientDaoMapper clientDaoMapper;

    @Resource
    private ChannelManageMapper channelManageMapper;

    @Autowired
    private HengDaProperties hengDaProperties;

    @Resource
    private ViolationInfoDaoMapper violationInfoDaoMapper;
    @Resource
    private HttpAPIService httpAPIService;
    @Value("${wz.token}")
    private String userToken;
    @Value("${wz.user}")
    private String user;
    @Value("${wz.api}")
    private String wwapi;
    @Value("http://api.bajiechewu.com/")
    private String wwurl;


    @Override
    public Integer saveBaseCar(BaseViolationBean baseViolationBean) {
        /*保存用户请求信息*/
        return clientDaoMapper.saveBaseCar(baseViolationBean);
    }

    @Override
    public BaseCarDO findLocalViolationRecord(String VehicleNo) {
        return null;
    }


    //万物
    @Override
    public ResponseUpstreamBean findViolationInfo(BaseViolationBean baseViolationBean, ChannelManageDO channel) {
        ResponseUpstreamBean responseUpstreamBean = null;
        /*根据用户请求参数查询上游*/
        Map<String, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("token", userToken);
        map.put("api", wwurl);
        map.put("cph", baseViolationBean.getVehicleNo());
        map.put("cx", baseViolationBean.getCarType());
        map.put("cjh", baseViolationBean.getFrameNo());
        map.put("fdj", baseViolationBean.getEngineNo());
        String provinceCode = CityCodeUtils.getProvinceCode(baseViolationBean.getVehicleNo().substring(0, 1));
        if (!"".equals(provinceCode)) {
            map.put("assign", provinceCode); //浙江
            System.out.println(provinceCode);
        }
        HttpResult httpResult = null;
        try {
            httpResult = httpAPIService.doPost(wwurl, map);
            String resultBody = httpResult.getBody();
            System.out.println("输出的body---" + resultBody);

            responseUpstreamBean = JSON.parseObject(resultBody, ResponseUpstreamBean.class);


            System.out.println("啦啦啦" + responseUpstreamBean);

            //将查询到的数据存入明细表里
            //TODO  判断返回码   生成统一的

            Integer code = responseUpstreamBean.getCode();
            System.out.println("根据code判断" + code);

            ViolationInfoDO violationInfoDO = new ViolationInfoDO();
            violationInfoDO.setCph(baseViolationBean.getVehicleNo());
            violationInfoDO.setCjh(baseViolationBean.getFrameNo());
            violationInfoDO.setFdj(baseViolationBean.getEngineNo());
            violationInfoDO.setData(resultBody);
            violationInfoDO.setChannelCode(baseViolationBean.getChannelCode());
            violationInfoDO.setOrigin("万物");

            violationInfoDO.setStatus(1); //1是成功   9是失败的

            violationInfoDaoMapper.saveViolationInfo(violationInfoDO);


            //TODO 这个地方可以优化    批量写入数据库
//            for (ViolationDetails details :responseUpstreamBean.getData()){
//                LocalViolationDetailDO localViolationDetailDO = new LocalViolationDetailDO();
//
//                violationDetailDaoMapper.saveViolationDetail(localViolationDetailDO);
//            }

            ChannelManageDO manageDO = new ChannelManageDO();
            System.out.println("修改之前先查询用户:" + baseViolationBean);

            manageDO.setId(channel.getId());
//
            manageDO.setTotalNumber(channel.getTotalNumber() + 1);
            manageDO.setRemainNumber(channel.getRemainNumber() - 1);
            Integer integer1 = channelManageMapper.updateChannelById(manageDO);


        } catch (Exception e) {
            e.printStackTrace();
        }
        //TODO 将请求到的信息保存到数据库
        System.out.println(httpResult);
        //TODO 将保存的数据返回

        return responseUpstreamBean;
    }

    @Override
    public ResponseUpstreamBean findWMViolationInfo(BaseViolationBean baseViolationBean, ChannelManageDO channel) {
        ResponseUpstreamBean responseUpstreamBean = new ResponseUpstreamBean();
        Map<String, Object> map = new HashMap<>();
        map.put("username", hengDaProperties.getLS_USER());
        String password = MD5Utils.Md5(hengDaProperties.getLS_USER()).toUpperCase();
        map.put("password", password);
        map.put("carNum", baseViolationBean.getVehicleNo());

        if (baseViolationBean.getEngineNo() != null) {
            map.put("engineNumber", baseViolationBean.getEngineNo());
        }
        if (baseViolationBean.getFrameNo() != null) {
            map.put("vin", baseViolationBean.getFrameNo());
        }
        map.put("carType", baseViolationBean.getCarType());
        map.put("area", baseViolationBean.getVehicleNo().substring(0, 1));
        map.put("time", String.valueOf(System.currentTimeMillis() / 1000L));
        String signStr = hengDaProperties.getLS_USER() + password + baseViolationBean.getVehicleNo() + baseViolationBean.getEngineNo() +
                baseViolationBean.getFrameNo() + baseViolationBean.getCarType() + baseViolationBean.getVehicleNo().substring(0, 1) +
                String.valueOf(System.currentTimeMillis() / 1000L);
        System.out.println(signStr);
        String sign = String.valueOf(MD5Utils.Md5(signStr));
        map.put("sign", sign);
        HttpResult httpResult = null;
        try {
            httpResult = httpAPIService.doPost(hengDaProperties.getLS_URL(), map);
            String resultBody = httpResult.getBody();
            System.out.println("输出的body" + resultBody);
            LocalWMResponseVO localWmResponseVO = JSON.parseObject(resultBody, LocalWMResponseVO.class);
            System.out.println("放入实体中" + localWmResponseVO);
            ViolationInfoDO violationInfoDO = new ViolationInfoDO();
            violationInfoDO.setCph(baseViolationBean.getVehicleNo());
            violationInfoDO.setCjh(baseViolationBean.getFrameNo());
            violationInfoDO.setFdj(baseViolationBean.getEngineNo());
            violationInfoDO.setData(resultBody);
            violationInfoDO.setChannelCode(baseViolationBean.getChannelCode());
            violationInfoDO.setOrigin("恒达");
            violationInfoDO.setType("历史");
            violationInfoDO.setStatus(1); //1是成功   9是失败的
            violationInfoDaoMapper.saveViolationInfo(violationInfoDO);

            //TODO 添加记录
            //如果请求成功
            if ("success".equals(localWmResponseVO.getState())) {

                responseUpstreamBean.setCph(baseViolationBean.getVehicleNo());
                responseUpstreamBean.setCjh(baseViolationBean.getFrameNo());
                responseUpstreamBean.setFdj(baseViolationBean.getEngineNo());
                responseUpstreamBean.setMsg("Success");
                responseUpstreamBean.setCode(ResultEnum.SUCCESS.getCode());
                //遍历请违章详情  存入返回的实体类中
                List<ViolationDetails> list = new ArrayList<>();
                for (LocalWMResponseVO.ResultEntity.HistorysEntity historysBean : localWmResponseVO.getResult().getHistorys()) {
                    ViolationDetails details = new ViolationDetails();
                    details.setWzsj(historysBean.getOccur_date());
                    details.setWzdd(historysBean.getOccur_area());
                    details.setWzxw(historysBean.getInfo());
                    details.setWzfk(historysBean.getMoney());
                    details.setWzjf(historysBean.getFen());
                    details.setCsmc(historysBean.getCity());
                    //details.setCsdm(details.getCsdm());
                    details.setWfdm(historysBean.getIllegal_code());

                    if ("未处理未缴款".equals(historysBean.getFine_status())){
                        details.setClbj("1");
                    }else if ("已处理已缴款".equals(historysBean.getFine_status())){
                        details.setClbj("3");
                    }
                    list.add(details);
                }
                responseUpstreamBean.setData(list);
//            if (violationInfo){}
                ChannelManageDO manageDO = new ChannelManageDO();
                System.out.println("修改之前先查询用户:" + channel);

                manageDO.setId(channel.getId());

                manageDO.setTotalNumber(channel.getTotalNumber() + 1);
                manageDO.setRemainNumber(channel.getRemainNumber() - 1);
                Integer integer1 = channelManageMapper.updateChannelById(manageDO);
            } else if ("fail".equals(localWmResponseVO.getState())) {
                responseUpstreamBean.setCph(baseViolationBean.getVehicleNo());
                responseUpstreamBean.setCjh(baseViolationBean.getFrameNo());
                responseUpstreamBean.setFdj(baseViolationBean.getEngineNo());
                responseUpstreamBean.setMsg(localWmResponseVO.getError_message());
                responseUpstreamBean.setCode(ResultEnum.FAIL.getCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //String resultBody = httpResult.getBody();
        //System.out.println("输出的body---"+resultBody);


        return responseUpstreamBean;
    }

    @Override
    public ResponseUpstreamBean findHDQGViolationInfo(BaseViolationBean baseViolationBean, ChannelManageDO channel) {
        ResponseUpstreamBean responseUpstreamBean = new ResponseUpstreamBean();
        Map<String, Object> map = new HashMap<>();
        map.put("username", hengDaProperties.getQG_USER());
        String password = MD5Utils.Md5(hengDaProperties.getQG_PASSWORD()).toUpperCase();
        System.out.println("密码:" + hengDaProperties.getQG_USER());
        System.out.println("密码加密后:" + password);
        map.put("password", password);
        map.put("carNum", baseViolationBean.getVehicleNo());
        if (baseViolationBean.getEngineNo() != null) {
            map.put("engineNumber", baseViolationBean.getEngineNo());
        } else {
            map.put("engineNumber", "000000");
        }
        if (baseViolationBean.getFrameNo() != null) {
            map.put("vin", baseViolationBean.getFrameNo());
        }else {
            map.put("vin","000000");
        }
        map.put("carType", baseViolationBean.getCarType());
        map.put("area", baseViolationBean.getVehicleNo().substring(0, 1));

        long time = System.currentTimeMillis() / 1000L;

        map.put("time", String.valueOf(time));
        String signStr = hengDaProperties.getQG_USER() + password + baseViolationBean.getVehicleNo() + map.get("engineNumber").toString() +
                map.get("vin").toString() + baseViolationBean.getCarType() + baseViolationBean.getVehicleNo().substring(0, 1) +
                String.valueOf(time);

        String sign = String.valueOf(MD5Utils.Md5(signStr));


        map.put("sign", sign);
        HttpResult httpResult = null;
        try {
            httpResult = httpAPIService.doPost(hengDaProperties.getQG_URL(), map);

            String resultBody = httpResult.getBody();
            System.out.println("输出的body" + resultBody);
            LocalWMResponseVO localWmResponseVO = JSON.parseObject(resultBody, LocalWMResponseVO.class);

            ViolationInfoDO violationInfoDO = new ViolationInfoDO();
            violationInfoDO.setCph(baseViolationBean.getVehicleNo());
            violationInfoDO.setCjh(baseViolationBean.getFrameNo());
            violationInfoDO.setFdj(baseViolationBean.getEngineNo());
            violationInfoDO.setData(resultBody);
            violationInfoDO.setChannelCode(baseViolationBean.getChannelCode());
            violationInfoDO.setOrigin("恒达");
            violationInfoDO.setType("全国");
            violationInfoDO.setStatus(1); //1是成功   9是失败的

            violationInfoDaoMapper.saveViolationInfo(violationInfoDO);

            //TODO 添加记录
            //如果请求成功
            if ("success".equals(localWmResponseVO.getState())) {

                responseUpstreamBean.setCph(baseViolationBean.getVehicleNo());
                responseUpstreamBean.setCjh(baseViolationBean.getFrameNo());
                responseUpstreamBean.setFdj(baseViolationBean.getEngineNo());
                responseUpstreamBean.setMsg("Success");
                responseUpstreamBean.setCode(ResultEnum.SUCCESS.getCode());
                //遍历请违章详情  存入返回的实体类中
                List<ViolationDetails> list = new ArrayList<>();
                for (LocalWMResponseVO.ResultEntity.HistorysEntity historysBean : localWmResponseVO.getResult().getHistorys()) {
                    ViolationDetails details = new ViolationDetails();
                    details.setWzsj(historysBean.getOccur_date());
                    details.setWzdd(historysBean.getOccur_area());
                    details.setWzxw(historysBean.getInfo());
                    details.setWzfk(historysBean.getMoney());
                    details.setWzjf(historysBean.getFen());
                    details.setCsmc(historysBean.getCity());
                    //details.setCsdm(details.getCsdm());
                    details.setWfdm(historysBean.getIllegal_code());

                    if ("未处理未缴款".equals(historysBean.getFine_status())){
                        details.setClbj("1");
                    }else if ("已处理已缴款".equals(historysBean.getFine_status())){
                        details.setClbj("3");
                    }

                    list.add(details);
                }
                responseUpstreamBean.setData(list);
                ChannelManageDO manageDO = new ChannelManageDO();
                manageDO.setId(channel.getId());
                manageDO.setTotalNumber(channel.getTotalNumber() + 1);
                manageDO.setRemainNumber(channel.getRemainNumber() - 1);
                Integer integer1 = channelManageMapper.updateChannelById(manageDO);
            } else if ("fail".equals(localWmResponseVO.getState())) {
                responseUpstreamBean.setCph(baseViolationBean.getVehicleNo());
                responseUpstreamBean.setCjh(baseViolationBean.getFrameNo());
                responseUpstreamBean.setFdj(baseViolationBean.getEngineNo());
                responseUpstreamBean.setMsg(localWmResponseVO.getError_message());
                responseUpstreamBean.setCode(ResultEnum.FAIL.getCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //String resultBody = httpResult.getBody();
        //System.out.println("输出的body---"+resultBody);
        return responseUpstreamBean;
    }
}
